import React, { useState, useEffect, useMemo } from 'react'
import { LeftOutline, MessageOutline, LikeOutline, StarOutline, MoreOutline } from 'antd-mobile-icons';
import { Badge, Toast } from 'antd-mobile';
import './Detail.less';
import { queryNewsInfo, queryStoryExtra, store, storeRemove } from "../api"
import SkeletonAgain from "../components/SkeletonAgain"
import actions from '../store/action';
import { connect } from 'react-redux';

function Detail(props) {
    const { navigate, params } = props;
    let [info, setInfo] = useState(null);
    let [extra, setExtra] = useState(null);
    useEffect(() => {
        (async () => {
            try {
                let news = await queryNewsInfo(params.id);
                setInfo(news);
            } catch (error) {
            }
        })()
    }, [])

    let link;
    const handleStyle = (res) => {
        let { css } = res;
        if (!Array.isArray(css)) return;
        css = css[0];
        if (!css) return;
        link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = css;
        document.head.appendChild(link)
    }

    const handleImage = (res) => {
        let imgDiv = document.querySelector(".img-place-holder");
        if (!imgDiv) return false;
        let timg = new Image;
        timg.src = res.image;
        timg.onload = () => {
            imgDiv.appendChild(timg)
        };
        timg.onerror = () => {
            imgDiv.parentNode.removeChild(imgDiv)
        }
    }

    useEffect(() => {
        if (info) {
            handleStyle(info);
            handleImage(info)
        }
        return () => {
            if (link) document.head.removeChild(link)
        }
    }, [info])

    useEffect(() => {
        try {
            (async () => {
                let res = await queryStoryExtra(params.id);
                setExtra(res)
            })()
        } catch (error) {
        }
    }, [])

    //=========下面的逻辑是关于登录/收藏的
    let {
        base: userInfo, queryUserInfoAsync,
        location,
        store: { list: storeList }, queryStoreListAsync, removeStoreListById
    } = props;

    useEffect(() => {
        (async () => {
            // 第一次渲染完:如果userInfo不存在,我们派发任务同步登录者信息
            if (!userInfo?.name) {
                let { info } = await queryUserInfoAsync();
                userInfo = info;
            }
            // 如果已经登录 && 没有收藏列表信息:派发任务同步收藏列表
            if (userInfo?.name && !storeList) {
                queryStoreListAsync();
            }
        })();
    }, []);

    let isStore = useMemo(() => {
        if (!storeList) return false;
        return storeList.some(item => {
            return +item.news.id === +params.id;
        });
    }, [storeList, params])

    const handleStore = async () => {
        if (!userInfo.name) {
            // 未登录
            Toast.show({
                icon: 'fail',
                content: '请先登录'
            });
            navigate(`/login?to=${location.pathname}`, { replace: true });
            return;
        }
        // 已经登录:收藏或者移除收藏
        if (isStore) {
            // 移除收藏
            let item = storeList.find(item => {
                return +item.news.id === +params.id;
            });
            if (!item) return;
            let { code } = await storeRemove(item.id);
            if (+code !== 0) {
                Toast.show({
                    icon: 'fail',
                    content: '移除失败'
                });
                return;
            }
            Toast.show({
                icon: 'success',
                content: '移除成功'
            });
            removeStoreListById(item.id); //告诉redux中也把这一项移除掉
            return;
        }
        // 收藏
        try {
            let { code } = await store(params.id);
            if (+code !== 0) {
                Toast.show({
                    icon: 'fail',
                    content: '收藏失败'
                });
                return;
            }
            Toast.show({
                icon: 'success',
                content: '收藏成功'
            });
            queryStoreListAsync(); //同步最新的收藏列表到redux容器中
        } catch (_) { }
    }

    return (
        <div className='detail-box'>
            {info ? <div className="content" dangerouslySetInnerHTML={{ __html: info.body }}>

            </div> : <SkeletonAgain />}

            <div className="tab-bar">
                <div className="back" onClick={() => { navigate(-1) }}><LeftOutline /></div>
                <div className="icons">
                    <Badge content={extra ? extra.comments : 0}>
                        <MessageOutline />
                    </Badge>
                    <Badge content={extra ? extra.popularity : 0}>
                        <LikeOutline />
                    </Badge>
                    <span className={isStore ? 'stored' : ''}
                        onClick={handleStore}>
                        <StarOutline />
                    </span>
                    <MoreOutline />
                </div>
            </div>
        </div>
    )
}

export default connect(
    state => ({
        base: state.base,
        store: state.store
    }),
    { ...actions.base, ...actions.store }
)(Detail)